package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableUserPhoneInfo;

public class TagUserPhoneInfo {
    public long uid;
    public String current_platform;
    public int platform_update_time;
    public String current_channel;
    public int channel_update_time;

    public TagUserPhoneInfo() {}

    public TagUserPhoneInfo(
            long uid,
            String current_platform,
            int platform_update_time,
            String current_channel,
            int channel_update_time) {
        this.uid = uid;
        this.current_platform = current_platform;
        this.platform_update_time = platform_update_time;
        this.current_channel = current_channel;
        this.channel_update_time = channel_update_time;
    }

    public static TagUserPhoneInfo init(long uid) {
        return new TagUserPhoneInfo(uid, "", 0, "", 0);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserPhoneInfo.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserPhoneInfo>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserPhoneInfo.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserPhoneInfo>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUserPhoneInfo> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserPhoneInfo-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserPhoneInfo>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUserPhoneInfo> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserPhoneInfo>, String>() {
                                    ValueState<TagUserPhoneInfo> userPhoneInfoVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        userPhoneInfoVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagUserPhoneInfo>(
                                                                        "userPhoneInfoVState",
                                                                        TagUserPhoneInfo.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserPhoneInfo> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        String platform = value.f1.getPlatform();
                                        String channel = value.f1.getChannel();
                                        int update_time = value.f1.getUpdated_at();
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("uid", uid);

                                        TagUserPhoneInfo tmpState = userPhoneInfoVState.value();
                                        TagUserPhoneInfo curState =
                                                tmpState == null
                                                        ? TagUserPhoneInfo.init(uid)
                                                        : tmpState;

                                        /**
                                         * platform和channel取不为NULL的最新的updated_at值，并更新ValueState
                                         *
                                         * <p>样例数据如下：
                                         * +----------+----------+----------+------------+
                                         * | uid      |platform  | channel  | updated_at |
                                         * +----------+----------+----------+------------+
                                         * |46166264  | Android  | ucredit  | 1672212417 |partition1
                                         * |46166264  | iPhone   | AppStore | 1672212418 |partition2
                                         * |46166264  | NULL     | ucredit  | 1672212419 |partition1
                                         * +----------+----------+----------+------------+
                                         */

                                        // 计算用户当前使用的操作系统
                                        if (update_time > curState.getPlatform_update_time()
                                                && !platform.equals("")) {
                                            if (!platform.equals(curState.getCurrent_platform())) {
                                                jsonObject.put("current_platform", platform);
                                                curState.current_platform = platform;
                                            }
                                            curState.platform_update_time = update_time;
                                        }

                                        // 计算用户当前的渠道
                                        if (update_time > curState.getChannel_update_time()
                                                && !channel.equals("")) {
                                            if (!channel.equals(curState.getCurrent_channel())) {
                                                jsonObject.put("current_channel", channel);
                                                curState.current_channel = channel;
                                            }
                                            curState.channel_update_time = update_time;
                                        }

                                        if (jsonObject.size() > 1) {
                                            out.collect(jsonObject.toString());
                                            userPhoneInfoVState.update(curState);
                                        }
                                    }
                                });
        return out;
    }

    public long getUid() {
        return uid;
    }

    public String getCurrent_platform() {
        return current_platform;
    }

    public long getPlatform_update_time() {
        return platform_update_time;
    }

    public String getCurrent_channel() {
        return current_channel;
    }

    public long getChannel_update_time() {
        return channel_update_time;
    }
}
